package com.baijiayun.liveuibase.devicetesting.fragment

import android.Manifest
import android.animation.ValueAnimator
import android.content.pm.PackageManager
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.baijiayun.liveuibase.R
import com.baijiayun.liveuibase.devicetesting.DeviceTestingViewModel
import com.baijiayun.liveuibase.utils.NetworkUtils
import com.baijiayun.liveuibase.utils.RxUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.bjy_base_fragment_device_testing_prepare.*
import java.util.concurrent.TimeUnit


class DeviceTestingPrepareFragment : Fragment() {
    private val deviceCheckResult = mutableListOf<Boolean>()
    private var disposableOfTime: Disposable? = null
    private var valueAnimator: ValueAnimator? = null
    private lateinit var viewModel : DeviceTestingViewModel

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.bjy_base_fragment_device_testing_prepare, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(requireActivity()).get(DeviceTestingViewModel::class.java)
        initView()
    }

    private fun initView() {
        bjy_base_fragment_device_testing_net_check_result_iv.visibility = View.INVISIBLE
        bjy_base_fragment_device_testing_camera_check_result_iv.visibility = View.INVISIBLE
        bjy_base_fragment_device_testing_speaker_check_result_iv.visibility = View.INVISIBLE
        bjy_base_fragment_device_testing_mic_check_result_iv.visibility = View.INVISIBLE
        bjy_base_fragment_device_testing_positive_btn.isEnabled = false
        bjy_base_fragment_device_testing_positive_btn.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_tip_text_color))
        bjy_base_fragment_device_testing_positive_btn.setText(R.string.bjy_base_device_testing_start)
        bjy_base_fragment_device_testing_net_check_iv.isEnabled = false
        bjy_base_fragment_device_testing_camera_check_iv.isEnabled = false
        bjy_base_fragment_device_testing_speaker_check_iv.isEnabled = false
        bjy_base_fragment_device_testing_mic_check_iv.isEnabled = false
        bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_try_to_connect)
        bjy_base_fragment_device_testing_progress_description_tv.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_device_testing_main_text_color))
        disposableOfTime = Observable.timer(200, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    bjy_base_device_testing_progress_bar.visibility = View.VISIBLE
                    checkPermission()
                }
    }

    private fun checkPermission() {
        bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_check_permission)
        valueAnimator = ValueAnimator.ofInt(0, 100)
        valueAnimator?.duration = 1000
        valueAnimator?.addUpdateListener {
            if (bjy_base_device_testing_progress_bar == null) {
                return@addUpdateListener
            }
            bjy_base_device_testing_progress_bar.progress = it.animatedValue as Int
            if (it.animatedValue == 100) {
                showPermissionResult()
            }
        }
        valueAnimator?.start()
        deviceCheckResult.clear()
        deviceCheckResult.add(!TextUtils.isEmpty(NetworkUtils.getIPAddress(activity)))
        deviceCheckResult.add(ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
        deviceCheckResult.add(true)
        deviceCheckResult.add(ActivityCompat.checkSelfPermission(activity!!, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)
    }

    private fun showPermissionResult() {
        valueAnimator?.cancel()
        bjy_base_device_testing_progress_bar.visibility = View.INVISIBLE
        bjy_base_fragment_device_testing_net_check_iv.isEnabled = deviceCheckResult[0]
        bjy_base_fragment_device_testing_camera_check_iv.isEnabled = deviceCheckResult[1]
        bjy_base_fragment_device_testing_speaker_check_iv.isEnabled = deviceCheckResult[2]
        bjy_base_fragment_device_testing_mic_check_iv.isEnabled = deviceCheckResult[3]
        bjy_base_fragment_device_testing_net_check_result_iv.visibility = View.VISIBLE
        bjy_base_fragment_device_testing_camera_check_result_iv.visibility = View.VISIBLE
        bjy_base_fragment_device_testing_speaker_check_result_iv.visibility = View.VISIBLE
        bjy_base_fragment_device_testing_mic_check_result_iv.visibility = View.VISIBLE
        bjy_base_fragment_device_testing_net_check_result_iv.isEnabled = deviceCheckResult[0]
        bjy_base_fragment_device_testing_camera_check_result_iv.isEnabled = deviceCheckResult[1]
        bjy_base_fragment_device_testing_speaker_check_result_iv.isEnabled = deviceCheckResult[2]
        bjy_base_fragment_device_testing_mic_check_result_iv.isEnabled = deviceCheckResult[3]
        if (!deviceCheckResult[0] && (!deviceCheckResult[1] || !deviceCheckResult[2] || !deviceCheckResult[3])) {
            bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_device_and_net_fail)
            bjy_base_fragment_device_testing_progress_description_tv.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_device_check_failed_text_color))
            bjy_base_fragment_device_testing_positive_btn.text = getString(R.string.bjy_base_window_loading_retry)
            bjy_base_fragment_device_testing_positive_btn.isEnabled = true
            bjy_base_fragment_device_testing_positive_btn.setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
            bjy_base_fragment_device_testing_positive_btn.setOnClickListener {
                initView()
            }
        } else if (!deviceCheckResult[0]) {
            bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_net_fail)
            bjy_base_fragment_device_testing_progress_description_tv.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_device_check_failed_text_color))
            bjy_base_fragment_device_testing_positive_btn.text = getString(R.string.bjy_base_window_loading_retry)
            bjy_base_fragment_device_testing_positive_btn.isEnabled = true
            bjy_base_fragment_device_testing_positive_btn.setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
            bjy_base_fragment_device_testing_positive_btn.setOnClickListener {
                initView()
            }
        } else if (!deviceCheckResult[1] || !deviceCheckResult[2] || !deviceCheckResult[3]) {
            bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_device_fail)
            bjy_base_fragment_device_testing_progress_description_tv.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_window_loading_device_check_failed_text_color))
            bjy_base_fragment_device_testing_positive_btn.text = getString(R.string.bjy_base_device_testing_to_authorize)
            bjy_base_fragment_device_testing_positive_btn.isEnabled = true
            bjy_base_fragment_device_testing_positive_btn.setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
            bjy_base_fragment_device_testing_positive_btn.setOnClickListener {
                val permissionList = mutableListOf<String>()
                if (!deviceCheckResult[1]) {
                    permissionList.add(Manifest.permission.CAMERA)
                }
                if (!deviceCheckResult[3]) {
                    permissionList.add(Manifest.permission.RECORD_AUDIO)
                }
                requestPermissions(permissionList.toTypedArray(), 0)
            }
        } else {
            bjy_base_fragment_device_testing_progress_description_tv.text = getString(R.string.bjy_base_device_testing_result_ok)
            bjy_base_fragment_device_testing_progress_description_tv.setTextColor(ContextCompat.getColor(context!!, R.color.bjy_base_device_testing_description_color))
            bjy_base_fragment_device_testing_positive_btn.text = getString(R.string.bjy_base_device_testing_start)
            bjy_base_fragment_device_testing_positive_btn.isEnabled = true
            bjy_base_fragment_device_testing_positive_btn.setTextColor(ContextCompat.getColor(context!!, R.color.base_white))
            bjy_base_fragment_device_testing_positive_btn.setOnClickListener {
                viewModel.setTestStep(DeviceTestingViewModel.TestStep.Start)
            }
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == 0) {
            for ((index, permission) in permissions.withIndex()) {
                if (permission == Manifest.permission.CAMERA && grantResults[index] == PackageManager.PERMISSION_GRANTED) {
                    deviceCheckResult[1] = true
                }
                if (permission == Manifest.permission.RECORD_AUDIO && grantResults[index] == PackageManager.PERMISSION_GRANTED) {
                    deviceCheckResult[3] = true
                }
            }
            showPermissionResult()
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        RxUtils.dispose(disposableOfTime)
    }
}